package com.flink.examples.functions;

import com.flink.examples.DataSource;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.List;

/**
 * @Description KeyBy算子：将数据流按照指定key进行分区
 * @Author JL
 * @Date 2020/09/14
 * @Version V1.0
 */
public class KeyBy {

    /**
     * 遍历集合，将用户按性别分成两类
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //如果有多个分区，则设置并行度需大于1,或者在算子上设置setParallelism(2)前行度，否则算子只有一个并行度，则计算结果始终只有一个分区
//        env.setParallelism(4);
        List<Tuple3<String,String,Integer>> tuple3List = DataSource.getTuple3ToList();
        DataStream<Tuple3<String,String,Integer>> dataStream = env.fromCollection(tuple3List);
        //注意：使用Integer进行分区时，会导致分区结果不对，转换成String类型输出key即可正确输出
        KeyedStream<Tuple3<String,String,Integer>, String> keyedStream = dataStream.keyBy(new KeySelector<Tuple3<String,String,Integer>, String>() {
            @Override
            public String getKey(Tuple3<String, String, Integer> tuple3) throws Exception {
                //f1为性别字段,以相同f1值（性别）进行分区
                return String.valueOf(tuple3.f1);
            }
        });

        //lambda
//        KeyedStream<Tuple3<String,String,Integer>, String> keyedStream = dataStream.keyBy((KeySelector<Tuple3<String, String, Integer>, String>) t3 -> t3.f1);
        //指定第几个字段做为key进行计算
//        KeyedStream<Tuple3<String,String,Integer>, Tuple> keyedStream = dataStream.keyBy(1);
        keyedStream.print().setParallelism(4);
        env.execute("flink keyBy job");
    }
}

/*
2> (张三,man,20)
4> (李四,girl,24)
2> (王五,man,29)
4> (刘六,girl,32)
2> (吴八,man,30)
4> (伍七,girl,18)
 */